﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Ams.Extensions;

namespace Ams.Mvc.Bootstrap.Annotations
{
    public class RequiredValidator<TDataAnnotation> : DataAnnotationsModelValidator<TDataAnnotation> where TDataAnnotation : RequiredAttribute
    {
        private readonly string _message;

        public RequiredValidator(ModelMetadata metadata, ControllerContext context, TDataAnnotation attribute)
            : base(metadata, context, attribute)
        {
            var display = String.IsNullOrWhiteSpace(metadata.DisplayName)
                              ? metadata.PropertyName.Titlize()
                              : metadata.DisplayName;
            _message = String.Format(attribute.ErrorMessage, display);
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = _message,
                ValidationType = "required"
            };

            return new[] { rule };
        }
    }
}